package me.hgj.jetpackmvvm.ledun.ui.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import me.hgj.jetpackmvvm.ledun.R

class RoundedImageView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {

    private val paint = Paint().apply {
        isAntiAlias = true
        isFilterBitmap = true
    }
    private var borderRadius: Float = 20f

    init {
        // 读取自定义属性
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundedImageView)
        borderRadius = typedArray.getDimension(R.styleable.RoundedImageView_borderRadius, 20f)
        typedArray.recycle()
    }

    override fun onDraw(canvas: Canvas) {
        val path = Path()
        val radii = floatArrayOf(
            borderRadius, borderRadius,
            borderRadius, borderRadius,
            borderRadius, borderRadius,
            borderRadius, borderRadius
        )
        val rect = RectF(0f, 0f, width.toFloat(), height.toFloat())
        path.addRoundRect(rect, radii, Path.Direction.CW)
        canvas.clipPath(path)
        super.onDraw(canvas)
    }
}